<template>
	<view  :style="{width:size+'px',height:size+'px'}">
		<canvas style="transform-origin: left top;" canvas-id="qrcode" id="qrcode"
			:style="{width:canvasSize+'px',height:canvasSize+'px',transform: `scale(${scale})`}"></canvas>
	</view>
</template>

<script>
	import UQRCode from '@/utils/qrcode.js';
	export default {
		name: "w-qrcode",
		props: {
			size: {
				type: Number,
				default: 200
			},
			content: {
				type: [String, Number],
				default: ''
			},
			color: {
				type: String,
				default: 'black'
			},
			bgColor: {
				type: String,
				default: 'white'
			}
		},
		watch: {
			content: {
				deep: true,
				immediate: true,
				handler(v) {
					if (v) {
						this.modules = []
						const qr = new UQRCode();
						// console.log('二维码内容：'+v)
						qr.data = v
						qr.make();
						this.modules = qr.modules
						this.build(qr.modules);
					}
				}
			}
		},
		computed: {
			canvasSize() {
				return this.modules.length * 10
			},
			scale() {
				// console.log(this.$u.getPx( this.size*2+'rpx'))
				return  this.$u.getPx( this.size*2+'rpx') / this.canvasSize
			}
		},
		data() {
			return {
				modules: []
			}
		},
		methods: {
			async build(rows) {
				await this.$u.sleep(300)
				// console.log(rows.length)
				this.$nextTick(()=>{
					const ctx = uni.createCanvasContext('qrcode', this);
					ctx.clearRect(0, 0, this.canvasSize, this.canvasSize)
					rows.forEach((cols, rowIndex) => {
						cols.forEach((point, colIndex) => {
							let isDraw = this.bgColor != 'unset' || point.isBlack
							if (isDraw) {
								ctx.setFillStyle(point.isBlack?this.color:this.bgColor)
								ctx.fillRect(rowIndex * 10, colIndex * 10, 10, 10)
								ctx.draw(true)
							}
					
							if (rowIndex == rows.length - 1 && colIndex == rows.length - 1) {
								this.getLocalPath()
							}
						})
					})
				})

			},
			getLocalPath() {
				let _this = this;
				uni.canvasToTempFilePath({
					canvasId: 'qrcode',
					success(res) {
						_this.$emit('change', res.tempFilePath)
					}
				})
			}
		}
	}
</script>
